from django_redis import get_redis_connection
from rest_framework import serializers

#没有模型，不采用ModelSerializer
class RegisterSmscodeSerializer(serializers.Serializer):
    #图片验证码
    text = serializers.CharField(label="图片验证码",max_length=4,min_length=4,required=True)
    #uuid，作为key匹配redis中的图片验证码
    image_code_id = serializers.UUIDField(label="uuid",required=True)

    def validate(self, attrs):
        #获取用户uuid
        # text = attrs['text']
        text = attrs.get('text')
        # image_code_id = attrs['image_code_id']
        image_code_id = attrs.get('image_code_id')
        #取出redis对应的值
          #链接redis
        redis_conn = get_redis_connection('code')
        #redis数据是bites类型
        redis_text = redis_conn.get('img_%s'%image_code_id)
        #对比
        #验证验证码是否已经过期
        if redis_text is None:
            raise serializers.ValidationError('验证码已过期')
        if redis_text.decode().lower() != text.lower():
            raise serializers.ValidationError('验证码错误')
        return attrs
